import React, { Component } from 'react'

import { Table, Space, Button, message, Modal, Form, Input, Select, Upload } from "antd"
import { fetchList } from '@/api/category'
import { getVideoList, uploadVideo, updateVideo } from "@/api/video"
import { UploadOutlined } from '@ant-design/icons'
import { valToFormData } from "@/utils/tools.js"
const { Option } = Select;

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
}

class VideoTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            list: [],
            categoryList: [],
            file: ''
        }
        // 获取分类信息
        this.getCategoryList();
        // 获取视频列表
        this.getVideoList();

    }
    formRef = React.createRef();
    // 表格配置项
    columns = [
        {
            title: '视频名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '视频Id',
            dataIndex: 'videoSourceId',
            key: 'videoSourceId',
        },
        {
            title: '视频类型',
            dataIndex: 'videoType',
            key: 'videoType',
        },
        {
            title: '视频URL',
            dataIndex: 'videoSourceUrl',
            key: 'videoSourceUrl',
        },
        {
            title: '视频封面',
            dataIndex: 'videoCoverUrl',
            key: 'videoCoverUrl',
        },
        {
            title: '所属分类',
            dataIndex: 'categoryName',
            key: 'categoryName',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => {

                return <Space size="middle" >
                    <button type="link" onClick={() => this.editVideo(text, record)}>编辑</button>
                    <button type="link" onClick={() => this.deleteVideo(text, record)}>删除</button>
                </Space>
            },
        },
    ]
    // 获取分类信息
    getCategoryList = async () => {
        const res = await fetchList({ page: 1, size: 100 });
        if (res.code === 0) {
            const { list: categoryList } = res.data;
            this.setState({
                categoryList,
            })
        }
    }
    // 获取视频列表
    getVideoList = async () => {
        const res = await getVideoList({ page: 1, size: 20 });
        if (res.code !== 0) return message.error(res.msg);
        const { list, pageSize, currentPage, totalCount } = res.data;
        this.setState({
            list,
            pageSize,
            currentPage,
            totalCount
        })
    }
    // 创建
    uploadVideo = () => {
        this.setState({
            visible: true
        })
    }

    // 编辑
    editVideo = (text) => {

    }
    //删除
    deleteVideo = (text) => {

    }

    // 分页
    onChange = (args) => {
        console.log(args)
    }

    // 创建保存
    handleCreate = async (val) => {
        const formData = valToFormData(val);
        const res = await uploadVideo(formData);
        if (res.code !== 0) return message.error(res.msg);
        message.success("保存成功");
        this.setState({
            visible: false
        })
    }

    // 更新保存
    handleUpdate = async (val) => {
        const formData = valToFormData(val);
        const res = await updateVideo(formData);
        if (res.code !== 0) return message.error(res.msg);
        message.success("更新成功");
        this.setState({
            visible: false
        })
    }

    // 保存
    handleOk = async () => {
        const val = await this.formRef.current.validateFields();
        const [file] = val.file;
        console.log(file)
        // return;
        if (this.state.id) {
            this.handleUpdate({ ...val, file: file.originFileObj })
        }
        this.handleCreate({ ...val, file: file.originFileObj })

    }
    // 取消
    handleCancel = () => {
        this.setState({
            visible: false
        })
    }
    onRemove = file => {
        console.log("=========", file)
    }
    beforeUpload = file => {
        // file 原始的文件对象
        console.log("file", file)
        return false;
    }
    normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    render() {
        const { list, categoryList, visible, totalCount = 0 } = this.state;
        const { onRemove, beforeUpload, normFile } = this;

        return (
            <>
                <Button type="primary" onClick={this.uploadVideo}>  上传视频 </Button>
                <Table
                    bordered
                    dataSource={list}
                    columns={this.columns}
                    onChange={this.onChange}
                    pagination={{
                        total: totalCount,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`
                    }}
                />
                {/* modal */}
                <Modal title="创建视频" visible={visible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <Form
                        {...formItemLayout}
                        ref={this.formRef}
                        labelAlign="right"
                    >
                        <Form.Item label="视频名称" name="title" rules={[{ required: true }]}>
                            <Input allowClear placeholder="请输入视频名称" />
                        </Form.Item>
                        <Form.Item label="视频分类" name="videoType" >
                            <Select
                                placeholder="请选择视频分类"
                                allowClear>
                                <Option value="1">普通</Option>
                                <Option value="2">连载</Option>
                                <Option value="3">电影</Option>
                            </Select>
                        </Form.Item>
                        {/* video_cover_url */}
                        <Form.Item label="视频封面" name="videoCoverUrl" >

                        </Form.Item>
                        <Form.Item label="所属分类" name="categoryId" rules={[{ required: true }]}>
                            <Select
                                placeholder="请选择所属分类"
                                allowClear
                            >
                                {
                                    categoryList.map((category) => <Option key={category.id} value={category.classId}>  {category.className} </Option>)
                                }
                            </Select>
                        </Form.Item>
                        {/* 要结合valuePropName，getValueFromEvent 进行校验  */}
                        <Form.Item
                            label="视频"
                            name="file"
                            valuePropName="fileList"
                            getValueFromEvent={normFile}
                            rules={[{ required: true, message: "请选择视频" }]}>
                            <Upload name="files" onRemove={onRemove} beforeUpload={beforeUpload} maxCount={1}>
                                <Button icon={<UploadOutlined />}>选择视频文件</Button>
                            </Upload>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
        );
    }
}

export default VideoTable;